const Koa = require("koa");
const cors = require("koa2-cors");
const Mongoose = require("mongoose");
const BodyParser = require("koa-bodyparser");
const Json = require("koa-json");
const Redis = require("koa-redis");
const Session = require("koa-session");
const User = require("./interface/router/users");
const Geo = require("./interface/router/geo");
const Search = require("./interface/router/search");
const Categroy = require("./interface/router/category");
const DBConfig = require("./dbs/config");
const passport = require("./interface/utils/passport");
const app = new Koa();

// 加密cookies的秘钥
app.proxy = true;
app.keys = ["mt", "liutzui"];

// redis middleware
// 参考 https://github.com/luin/ioredis

// -----------------数据库连接-------------------------
Mongoose.set("useFindAndModify", false);
Mongoose.connect(DBConfig.mongodb.dbs, {
  user: DBConfig.mongodb.user,
  pass: DBConfig.mongodb.pass,
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true
});
let db = Mongoose.connection;
db.on("connected", err => {
  if (err) console.log("数据库连接失败", err);
  console.log("数据库连接成功");
});

// -----------------数据库连接-------------------------

// -----------------自定义中间件-------------------------
// 处理运行错误中间件
const ErrMiddle = async (ctx, next) => {
  try {
    await next();
  } catch (error) {
    console.log(error);
    return (ctx.body = {
      code: 1,
      msg: error.message || "发生错误,请稍后重试"
    });
  }
};
// -----------------自定义中间件-------------------------

// -----------------中间件-------------------------
app.use(ErrMiddle);
app.use(
  Session(
    {
      // key: cookie name defaulting to koa.sid
      // prefix: session prefix for store, defaulting to koa:sess:
      key: "mt",
      prefix: "mt:uid:",
      maxAge: 1000 * 60 * 10,
      store: new Redis({
        port: DBConfig.redis.port,
        host: DBConfig.redis.host,
        password: DBConfig.redis.password
      })
    },
    app
  )
);
app.use(BodyParser());
app.use(cors());
app.use(Json());
app.use(passport.initialize());
app.use(passport.session());
app.use(User.routes()).use(User.allowedMethods());
app.use(Geo.routes()).use(Geo.allowedMethods());
app.use(Search.routes()).use(Search.allowedMethods());
app.use(Categroy.routes()).use(Categroy.allowedMethods());

// -----------------中间件-------------------------

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`server in running ${PORT}...`);
});
